import { Injectable } from '@angular/core';
import { CartItem } from '../ngrx/cart-store/cart.reducer';

@Injectable({
  providedIn: 'root',
})
export class UtilsService {
  constructor() {}
  deepClone(obj: any): any {
    let objClone: any = Array.isArray(obj) ? [] : {};
    if (obj && typeof obj === 'object') {
      for (let key in obj) {
        if (obj.hasOwnProperty(key)) {
          if (obj[key] && typeof obj[key] === 'object') {
            objClone[key] = this.deepClone(obj[key]);
          } else {
            objClone[key] = obj[key];
          }
        }
      }
    }
    return objClone;
  }
  _deepClone(obj: Array<any> | object) {
    let objClone: any = Array.isArray(obj) ? [] : {};
    if (Array.isArray(obj)) {
      obj.forEach((item: any, index) => {
        if (Array.isArray(obj)) {
          objClone[index] = this._deepClone(item);
        } else {
          objClone[index] = item;
        }
      });
    } else {
      for (const key in obj) {
        if (obj.hasOwnProperty(key)) {
          if (obj[key] && typeof obj[key] === 'object') {
            objClone[key] = this._deepClone(obj[key]);
          } else {
            objClone[key] = obj[key];
          }
        }
      }
    }
    return objClone;
  }
  filterCarlist(
    cartList: CartItem[],
    product: CartItem,
    select: boolean = false
  ) {
    let list = [...cartList];
    let oldProduct = false;
    for (let i = 0; i < list.length; i++) {
      if (list[i].id === product.id) {
        const item = this.deepClone(product);
        if (!select) item.count = list[i].count + product.count;
        list.splice(i, 1);
        list.splice(i, 0, item);
        oldProduct = true;
        break;
      }
    }
    return {
      cartList: list,
      isChange: oldProduct,
    };
  }
}
